/**
 * Created by LXhan on 2017/10/5.
 */
var tableEle;//电表
var tableWater;//水表
var activebuildingID = '';//选中楼宇ID
var code = '';//查询条件编号
var time = getNowFormatDate();//查询条件日期
var displaySwitch = 0;//显示隐藏开关
var $;
var table
layui.use(['jquery', 'table', 'laydate', 'form', 'layer', 'element'], function () {
    table= layui.table;
    var form = layui.form;
    var element = layui.element;
    $ = layui.jquery;
    var laydate = layui.laydate;
    //执行一个laydate实例
    laydate.render({
        elem: '#eledate'
        ,type:'month'
    });
    laydate.render({
        elem: '#waterdate'
        ,type:'month'
    });
    activebuildingID = QueryUtils.GetQueryString('activebuildingID');
    <!--**********************水电表管理*************************-->
    //电表展示已知数据
    tableEle = table.render({
        elem: '#dbgl'
        , url: '/hydropowerdetail/list'
        , where: {type: 'b938139a48ed4344a11a7180b48eede6', buildingId: activebuildingID, code: code,time:time}
        , cols: [[ //标题栏
            {checkbox: true, LAY_CHECKED: true} //默认全选
            , {field: 'CODE', title: '电表编号', width: 150, templet: '#emptyTemp'}
            , {field: 'BYNAME', title: '别名', width: 150, templet: '#emptyTemp'}
            , {field: 'ROOM_NUM', title: '项目编号', width: 150, templet: '#emptyTemp'}
            , {field: 'LAST_DEGREES', title: '上次读数', width: 150, templet: '#emptyTemp'}
            , {field: 'LAST_DATE', title: '上次读表时间', width: 150, templet: '#emptyTemp'}
            , {field: 'CUR_DEGREES', title: '当前读数', width: 150,  style: 'cursor: pointer;', templet: '#emptyTemp'}
            , {field: 'CUR_DATE', title: '当前读表时间', width: 150, templet: '#emptyTemp'}
            , {fixed: 'right', title: '操作', width: 150, align: 'center', templet: '#dbglBar'}
        ]]
        , id: 'ET'
        , page: true
        , height: 400
        , done: function (res, curr, count) {
            setGenRecordDisplay(count,displaySwitch);
            var list = res.data;
            $.each(list,function (i,item) {
                if (item.IS_BILL == 0) {
                    item.edit = true;
                } else {
                    item.edit = false;
                }
            })
            //TODO:设置可编辑单元格
            setEditEnable({
                data: list,//表格列表数据
                editConditions: "edit",//数据源中标识可编辑的字段
                rowKey: "CODE",//数据源中查找行的标识字段（对应表头）
                column: "CUR_DEGREES"//可编辑的字段，表格列（对应表头）
            });

        }
    });



    //编辑电表
    table.on("edit(power)", function(obj) {
        var value = obj.value,
            data = obj.data,
            field = obj.field;
        // console.log("edit data=>", obj);
        // layer.msg("[ID: " + data.ID + "] " + field + " 字段更改为：" + value);
        editCurDegrees(data.ID, value);
        // tableEle.reload();
    });

    //水表展示已知数据
    tableWater = table.render({
        elem: '#sbgl'
        , url: '/hydropowerdetail/list'
        , where: {type: 'ae5806f8184546208411b99e6117eaa2', buildingId: activebuildingID, code: code,time:time}
        , cols: [[ //标题栏
            {checkbox: true, LAY_CHECKED: true} //默认全选
            , {field: 'CODE', title: '水表编号', width: 150, templet: '#emptyTemp'}
            , {field: 'BYNAME', title: '别名', width: 150, templet: '#emptyTemp'}
            , {field: 'ROOM_NUM', title: '项目编号', width: 150, templet: '#emptyTemp'}
            , {field: 'LAST_DEGREES', title: '上次读数', width: 150, templet: '#emptyTemp'}
            , {field: 'LAST_DATE', title: '上次读表时间', width: 150, templet: '#emptyTemp'}
            , {field: 'CUR_DEGREES', title: '当前读数', width: 150,  style: 'cursor: pointer;', templet: '#emptyTemp'}
            , {field: 'CUR_DATE', title: '当前读表时间', width: 150, templet: '#emptyTemp'}
            , {fixed: 'right', title: '操作', width: 150, align: 'center', templet: '#sbglBar'}
        ]]
        , id: 'WT'
        , page: true
        , height: 400
        , done: function (res, curr, count) {
            setGenRecordDisplayWater(count);
            var list = res.data;
            $.each(list,function (i,item) {
                if (item.IS_BILL == 0) {
                    item.edit = true;
                } else {
                    item.edit = false;
                }
            })
            //TODO:设置可编辑单元格
            setEditEnable({
                data: list,//表格列表数据
                editConditions: "edit",//数据源中标识可编辑的字段
                rowKey: "CODE",//数据源中查找行的标识字段（对应表头）
                column: "CUR_DEGREES"//可编辑的字段，表格列（对应表头）
            });
        }
    });

    //编辑水表
    table.on("edit(water)", function(obj) {
        var value = obj.value,
            data = obj.data,
            field = obj.field;
        // console.log("edit data=>", obj);
        // layer.msg("[ID: " + data.ID + "] " + field + " 字段更改为：" + value);
        editCurDegrees(data.ID, value);
        // tableWater.reload();
    });

    //table监听事件

    table.on('tool(water)', function (obj) {
        var data = obj.data;
        //修改当前读数
        if (obj.event === 'setCurWater') {
            if (data.IS_BILL == 0) {
                layer.prompt({
                    formType: 2
                    , title: '修改[' + data.CODE + '] 的当前读数'
                    , value: data.CUR_DEGREES
                }, function (value, index) {
                    layer.close(index);
                    editCurDegrees(data.ID, value);
                    tableWater.reload();
                });
            } else {
                layer.msg('该条记录账单已生成，不可修改！');
            }

        } else if (obj.event === 'genRecord') {
            var data = genBill(data.EID, data.TYPE);
            if (data.errcode == "00") {
                tableWater.reload();
            } else {
                layer.msg(data.errmsg);
            }
        }
    });
    table.on('tool(power)', function (obj) {
        var data = obj.data;
        //修改当前读数
        if (obj.event === 'setCur') {
            if (data.IS_BILL == 0) {
                layer.prompt({
                    formType: 2
                    , title: '修改[' + data.CODE + '] 的当前读数'
                    , value: data.CUR_DEGREES
                }, function (value, index) {
                    layer.close(index);
                    editCurDegrees(data.ID, value);
                    tableEle.reload();
                });
            } else {
                layer.msg('该条记录账单已生成，不可修改！');
            }

        } else if (obj.event === 'genRecord') {
            var data = genBill(data.EID, data.TYPE);
            if (data.errcode == "00") {
                tableEle.reload();
            } else {
                layer.msg(data.errmsg);
            }
        }
    });



});
//电表生成记录按钮
function genElecRecord() {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genrocord",
        async: true,
        data: {
            type: 'b938139a48ed4344a11a7180b48eede6',
            buildingId: activebuildingID
        },
        success: function (rs) {
            tableEle.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}
//水表生成记录按钮
function genWaterRecord() {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genrocord",
        async: true,
        data: {
            type: 'ae5806f8184546208411b99e6117eaa2',
            buildingId: activebuildingID
        },
        success: function (rs) {
            tableWater.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}
/*
 批量生成账单电表
 */
function genElecBillMany() {
    var data = table.checkStatus('ET').data;
    console.log(data);
    var pd = initDatas(data);
    genBillMany(pd);
    tableEle.reload();
}
/*
 批量生成账单水表
 */
function genWaterBillMany() {
    var data = table.checkStatus('WT').data;
    var pd = initDatas(data);
    genBillMany(pd);
    tableWater.reload();
}
//水电表查询按钮
function search(type) {
    displaySwitch = 1;
    if (type == 0) {
        code = $("#elecode").val();
        time = $("#eledate").val();
        if(time.length > 0){
            time +='-'+'01'
        }else {
            time = getNowFormatDate();
        }
        tableEle.reload({
            where: {type: 'b938139a48ed4344a11a7180b48eede6', buildingId: activebuildingID, code: code,time:time}
        });
    } else {
        code = $("#watercode").val();
        time = $("#waterdate").val();
        if(time.length > 0){
            time +='-'+'01'
        }else {
            time = getNowFormatDate();
        }
        tableWater.reload({
            where: {type: 'ae5806f8184546208411b99e6117eaa2', buildingId: activebuildingID, code: code,time:time}
        });
    }
}
/*生成本月电表抄表记录按钮是否显示*/
function setGenRecordDisplay(count,t) {
    if(t == 0){
        if (count > 0) {
            $("#genElecRecord").hide();
            $("#genElecBillMany").show();
        } else {
            $("#genElecRecord").show();
            $("#genElecBillMany").hide();
        }
    }
}

/*生成本月水表抄表记录按钮是否显示*/
function setGenRecordDisplayWater(count) {
    if (count > 0) {
        $("#genWaterRecord").hide();
        $("#genWaterBillMany").show();
    } else {
        $("#genWaterRecord").show();
        $("#genWaterBillMany").hide();
    }
}
//修改当前读数
function editCurDegrees(id, curDegrees) {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/edit",
        async: true,
        data: {
            id: id,
            curDegrees: curDegrees
        },
        success: function (rs) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

/*
 生成当月记录
 */
function genCurmonthRecs(type) {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genrocord",
        async: true,
        data: {
            type: type,
            buildingId: '13d18abb6e6c4314b6c29969cd4d5e25'
        },
        success: function (rs) {
            location.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

//生成账单
function genBill(eid, type) {
    var result;
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genbillnew",
        async: false,
        data: {
            eid: eid,
            type: type
        },
        success: function (rs) {
            result = rs;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
    return result;
}

//批量生成账单封装数据
function initDatas(data) {
    var rs;
    $.each(data, function (i, info) {
        if (i == 0) {
            rs = info.EID + "," + info.TYPE;
        } else {
            rs += "#" + info.EID + "," + info.TYPE;
        }

    })
    return rs;
}

/*
 批量生成账单
 */
function genBillMany(pd) {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genbillmanynew",
        async: false,
        data: {
            data: pd
        },
        success: function (rs) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}



function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
        // + " " + date.getHours() + seperator2 + date.getMinutes()
        // + seperator2 + date.getSeconds();
    // var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    //     + " " + date.getHours() + seperator2 + date.getMinutes()
    //     + seperator2 + date.getSeconds();
    return currentdate;
}


//**************************************************************************************//

// region 获取可编辑的单元格
/**
 * 获取可编辑的单元格
 *
 * @param {object} option
 * {
   *    data: 表格数据源
   *    editConditions: 数据源中判断是否可编辑的字段
   *    rowKey: 可编辑单元格所在行的唯一标示字段
   *    column: 可编辑单元格所在的列
   * }
 */
function setEditEnable(option) {
    // region 可编辑单元格相关数据
    var editCellInfo = {
        rows: [],
        selectors: []
    };
    // endregion

    var config = {
        data: option.data || [],
        editConditions: option.editConditions || "",
        rowKey: option.rowKey || "",
        column: option.column || ""
    };
    config.data.map(function(item) {
        if (item[config.editConditions]) {
            editCellInfo.rows.push(item);
            editCellInfo.selectors.push('td[data-field="' + (config.rowKey) + '"][data-content="' + item[config.rowKey] + '"]');
        }
    });
    $(editCellInfo.selectors.join(","))
        .closest("tr")
        .find('[data-field="' + config.column + '"]')
        .attr("data-edit", true);

    // console.log('可编辑元素所在行=>',editCellInfo.selectors)
    // console.log('可编辑元素=>',$(editCellInfo.selectors.join(",")).closest("tr").find('[data-field="' + config.column + '"]'))

    // region 键盘事件监听
    window.addEventListener('keyup',function(event){
        // console.log(event.keyCode,event)//下 40 上 38 tab 9
        if(event.keyCode === 40 || event.keyCode === 38){
            var $eventRow = $(event.target).closest('tr');
            var dataContent = $eventRow.find('td[data-field="' + (config.rowKey || "ID") + '"]').attr('data-content');
            var index = editCellInfo.selectors.indexOf('td[data-field="' + (config.rowKey || "ID") + '"][data-content="' + dataContent + '"]');
            (index < 0 && (index = editCellInfo.selectors.length - 1)) || (index > editCellInfo.selectors.length - 1 && (index = 0));
            $(event.target).blur();
            $(editCellInfo.selectors[index + ((event.keyCode === 40 && 1) || (event.keyCode === 38 && -1))]).siblings('[data-field="'+config.column+'"]').click().find('.layui-table-edit').focus();
        }
    });
}
